package com.study.homework.concurrent;


/**
 * @author andys
 *
 *子线程循环10次, 接着主线程循环100,
 *接着又回到子线程循环10次,接着再回到主线程又循环100次,
 *如此循环50次
 *
 *
 */
public class TestThread2 {
	
	public static void main(String[] args) {
		
		final Business business = new Business();
		new Thread(new Runnable(){

			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					business.sub(i);
				}
				
			}}).start();
		for (int i = 0; i < 50; i++) {
			business.main(i);
		}
		
	}
}
class Business{
	private boolean bShouldSub = true;
	
	public synchronized void sub(int j){
//		if (!bShouldSub) {
		while (!bShouldSub) { //这里使用while比较好
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 1; i <= 10; i++) {
			System.out.println("sub thread sequece of" + i+"; loop of"+j);
		}
		
		bShouldSub = false;
		this.notify();
	}
	public synchronized void main( int j){
		if (bShouldSub) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 1; i <= 100; i++) {
			System.out.println("main thread sequece of" + i+"; loop of"+j);
		}
		
		bShouldSub = true;
		this.notify();
	}
}
